#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Pre-commit 代码质量检查脚本"""
import io
import subprocess
import sys
from pathlib import Path

# Fix Windows console encoding
if sys.platform == 'win32':
    if hasattr(sys.stdout, 'buffer'):
        sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
    if hasattr(sys.stderr, 'buffer'):
        sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8', errors='replace')

def run_command(cmd: str) -> tuple[int, str, str]:
    """运行命令并返回结果"""
    result = subprocess.run(
        cmd,
        shell=True,
        capture_output=True,
        text=True,
        encoding='utf-8',
        errors='replace'
    )
    return result.returncode, result.stdout, result.stderr

def main() -> int:
    """主函数"""
    # __file__ is in .precommit/checkers/, so parent.parent.parent gets to project root
    PROJECT_ROOT = Path(__file__).parent.parent.parent
    BACKEND_PATH = PROJECT_ROOT / "backend" / "app"

    CONFIG_FILE = PROJECT_ROOT / "pyproject.toml"

    # Step 1: 先尝试自动修复
    print("[Pre-commit] Step 1: Ruff 自动修复 (--fix)...")
    fix_code, fix_out, fix_err = run_command(f"ruff check {BACKEND_PATH} --fix --config {CONFIG_FILE}")

    if fix_code == 0:
        print("[Ruff] 自动修复成功，无剩余问题")
    elif "Fixed" in fix_out:
        print("[Ruff] 部分问题已自动修复")
        # 提取修复数量
        import re
        fixed_match = re.search(r'Fixed (\d+)', fix_out)
        if fixed_match:
            print(f"       已修复 {fixed_match.group(1)} 个问题")

    # Step 2: 检查剩余问题
    print("[Pre-commit] Step 2: Ruff 检查剩余问题...")
    ruff_code, ruff_out, ruff_err = run_command(f"ruff check {BACKEND_PATH} --config {CONFIG_FILE}")

    if ruff_code != 0:
        print(f"[Ruff] 发现问题:")
        print(ruff_out)
        if ruff_err:
            print(ruff_err)
        print()

    print("[Pre-commit] 运行 MyPy 类型检查...")
    mypy_code, mypy_out, mypy_err = run_command(f"mypy {BACKEND_PATH} --strict")

    if mypy_code != 0:
        print(f"[MyPy] 发现问题:")
        print(mypy_out)
        if mypy_err:
            print(mypy_err)
        print()

    # 判断是否有错误
    has_errors = (ruff_code != 0) or (mypy_code != 0)

    if has_errors:
        print("=" * 60)
        print("[Pre-commit] 代码检查失败")
        print("=" * 60)
        print()
        print("修复建议:")
        print("  1. 查看上述错误详情")
        print("  2. 自动格式化: black backend/app && isort backend/app")
        print("  3. 查看完整报告: cat reports/last_error.log")
        print("  4. 跳过检查(紧急): git commit --no-verify")
        print()
        return 1
    else:
        print("[Pre-commit] 所有检查通过!")
        return 0

if __name__ == "__main__":
    sys.exit(main())
